<template>
  <a-modal
    v-model:visible="visible"
    :title="title"
    :fullscreen="isMobile()"
    :mask-closable="true"
    @ok="save"
  >
    <a-tree
      ref="TreeRef"
      size="mini"
      checkable
      :data="treeData"
      check-strictly
      v-model:checked-keys="menuIds"
      :fieldNames="{ key: 'id' }"
    ></a-tree>
  </a-modal>
</template>

<script setup lang="ts">
import { isMobile } from '@/utils/common'
import type { TreeInstance } from '@arco-design/web-vue'
import { getSystemMenuOptions, getSystemRoleMenuIds, MenuOptionsItem } from '@/api'
import { generateTitle } from '@/utils/i18n'

const visible = ref(false)
const title = computed(() => `分配权限`)

const TreeRef = ref<TreeInstance>()
const treeData = ref<MenuOptionsItem[]>([])

const menuIds = ref<string[]>([])

const getTreeData = async () => {
  const res = await getSystemMenuOptions()
  const data = res.data
  data.forEach((item) => {
    item.title = generateTitle(item.title) as string
    if (item.children) {
      item.children.forEach((child) => {
        child.title = generateTitle(child.title) as string
      })
    }
  })
  treeData.value = data
  await nextTick(() => {
    TreeRef.value?.expandAll()
  })
}

getTreeData()

const open = (data: { code: string; title: string }) => {
  menuIds.value = []
  getSystemRoleMenuIds({ role: data.code }).then((res) => {
    menuIds.value = res.data
  })
  visible.value = true
}

defineExpose({ open })

const save = () => {}
</script>

<style scoped lang="scss"></style>
